package com.hejing.线程安全问题;

import java.util.concurrent.locks.ReentrantLock;

/**
 * ClassName: WindowTest01
 * Package: com.hejing.线程安全问题
 * Description:
 *      使用继承Thread的方式，实现卖票
 * @Author: HeJing
 * @Create: 2023-04-14 19:31
 * @Version: 1.0
 */
public class LockTest01 {
    public static void main(String[] args) {
        SaleTicket01WithLock s1 = new SaleTicket01WithLock();
        SaleTicket01WithLock s2 = new SaleTicket01WithLock();
        SaleTicket01WithLock s3 = new SaleTicket01WithLock();

        s1.setName("窗口1");
        s2.setName("窗口2");
        s3.setName("窗口3");

        s1.start();
        s2.start();
        s3.start();
    }
}

class SaleTicket01WithLock extends Thread {

    static int ticket = 100;

    private static final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while(true) {
            try{
                Thread.sleep(10);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            try {
                lock.lock();
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + "售票，票号: " + (101 - ticket));
                    ticket--;
                } else break;
            } finally {
                lock.unlock();
            }
        }
    }
}




















